package com.qiuling.iot.config;

import com.alibaba.fastjson.JSONObject;
import com.qiuling.iot.entity.SocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * @Author：zhangqiang
 * @Description：
 * @Date：Created in 21:42 2020/2/23
 * @Modified By：
 */
@Configuration
@Slf4j
@PropertySource("classpath:config.properties")
public class SocketServerConfig {

    @Value("${SocketServer.port}")
    private int port;

    @Bean
    public SocketServer socketServer() {
        SocketServer socketServer = new SocketServer(port);
        /**
         * 验证登录设备信息，验证失败将不会开启服务器线程
         * 验证成功，则由ConnectionThread连接池验证心跳信息和处理逻辑
         */
        socketServer.setLoginHandler(equipmentCode -> {
            if(StringUtils.isNotBlank(equipmentCode)) {
                log.info("处理socket用户身份验证,equipmentCode:{}", equipmentCode);
                return true;
            } else {
                return false;
            }

        });
        socketServer.setMessageHandler((connection, serverReceiveRespVO) -> log
                .info("处理socket消息,equipmentCode:{},receiveDto:{}", connection.getEquipmentCode(),
                        JSONObject.toJSONString(serverReceiveRespVO)));
        socketServer.start();
        return socketServer;
    }
}
